<template>
  <LayoutContainer>
    <UiLoadingPanel v-if="pending" />
    <div v-else>
      <h2>Editer la zone de résidence</h2>
      <UiForm
        ref="form"
        :model="ResidenceArea"
        :entity="residence_areas"
        :submitActions="submitActions"
      >
        <UiInputText
          field="label"
          v-model="residence_areas.label"
          :rules="rules()"
        />
      </UiForm>
    </div>
    <v-btn class="mr-12" @click="quit">
      {{ $t('back') }}
    </v-btn>
  </LayoutContainer>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import ResidenceArea from '~/models/Billing/ResidenceArea'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { AnyJson } from '~/types/data'
import { SUBMIT_TYPE } from '~/types/enum/enums'

const i18n = useI18n()
const { fetch } = useEntityFetch()
const router = useRouter()
const route = useRoute()

const residenceId = ref(parseInt(route.params.id as string))

const goBackRoute = { path: `/parameters`, query: { tab: 'residenceAreas' } }

const submitActions = computed(() => {
  let actions: AnyJson = {}
  actions[SUBMIT_TYPE.SAVE_AND_BACK] = goBackRoute
  return actions
})

const { data: residence_areas, pending } = fetch(
  ResidenceArea,
  residenceId.value
)

const rules = () => [
  (label: string | null) =>
    (label !== null && label.length > 0) || i18n.t('please_enter_a_value'),
]

const quit = () => {
  router.push(goBackRoute)
}
</script>
